<template>
  <div class="resource-catalog">
    <!-- 顶部工具栏 -->
    <div class="page-header">
      <div class="header-left">
        <h2>资源目录管理</h2>
        <a-tag
          v-if="currentBusinessType"
          :color="getBusinessTypeColor(currentBusinessType)"
        >
          {{ currentBusinessTypeName }}
        </a-tag>
      </div>
      <div class="header-actions">
        <a-space>
          <a-button type="primary" @click="handleCreateResource">
            <IconifyIcon icon="ant-design:plus-outlined" />
            创建资源
          </a-button>
          <a-button @click="handleBatchImport">
            <IconifyIcon icon="ant-design:upload-outlined" />
            批量导入
          </a-button>
          <a-button @click="handleExport">
            <IconifyIcon icon="ant-design:download-outlined" />
            导出
          </a-button>
        </a-space>
      </div>
    </div>

    <div class="catalog-layout">
      <!-- 左侧资源目录（可折叠） -->
      <ResourceSidebar
        :collapsed="sidebarCollapsed"
        :tree-data="resourceTree"
        :expanded-keys="expandedKeys"
        :selected-keys="selectedKeys"
        :loading="treeLoading"
        :active-category="activeCategory"
        :custom-tags="customTags"
        :selected-custom-tag="selectedCustomTag"
        @toggle-collapse="toggleSidebar"
        @search="handleTreeSearch"
        @expand="handleTreeExpand"
        @select="handleTreeSelect"
        @right-click="handleTreeRightClick"
        @category-change="handleCategoryChange"
        @custom-tag-click="handleCustomTagClick"
      />

      <!-- 主内容区 -->
      <div v-if="currentViewMode === 'list'" class="main-content list-panel">
        <ResourceList
          :title="getListTitle()"
          :total-count="currentResources.length"
          :data-source="currentResources"
          :loading="listLoading"
          :pagination="listPagination"
          :selected-resource-id="selectedResourceId"
          :breadcrumb-items="breadcrumbItems"
          :columns="listColumns"
          @search="handleListSearch"
          @filter-change="handleFilterChange"
          @table-change="handleTableChange"
          @resource-click="handleResourceClick"
          @view="handleView"
          @edit="handleEdit"
          @delete="handleDelete"
          @breadcrumb-click="handleBreadcrumbClick"
        />
      </div>

      <!-- 资源详情面板（当选中叶子节点时显示） -->
      <div
        v-else-if="currentViewMode === 'detail'"
        class="main-content detail-panel"
      >
        <div class="detail-header">
          <a-breadcrumb>
            <a-breadcrumb-item v-for="item in breadcrumbItems" :key="item.key">
              <a @click="handleBreadcrumbClick(item)">{{ item.title }}</a>
            </a-breadcrumb-item>
          </a-breadcrumb>
          <div class="detail-title">
            <h3>{{ selectedResource?.name }}</h3>
            <a-tag
              :color="getResourceTypeColor(selectedResource?.resource_type)"
            >
              {{ getResourceTypeLabel(selectedResource?.resource_type) }}
            </a-tag>
          </div>
        </div>

        <div class="detail-content">
          <a-tabs v-model="activeTab">
            <a-tab-pane key="basic" tab="基本信息">
              <a-descriptions :column="2" bordered size="small">
                <a-descriptions-item label="资源名称">
                  {{ selectedResource?.name }}
                </a-descriptions-item>
                <a-descriptions-item label="资源编码">
                  {{ selectedResource?.code }}
                </a-descriptions-item>
                <a-descriptions-item label="资源类型">
                  {{ getResourceTypeLabel(selectedResource?.resource_type) }}
                </a-descriptions-item>
                <a-descriptions-item label="业务类型">
                  {{ selectedResource?.business_type }}
                </a-descriptions-item>
                <a-descriptions-item label="状态">
                  <a-tag
                    :color="selectedResource?.status === 1 ? 'green' : 'red'"
                  >
                    {{ selectedResource?.status === 1 ? '启用' : '禁用' }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="创建时间">
                  {{ selectedResource?.create_time }}
                </a-descriptions-item>
                <a-descriptions-item label="描述" :span="2">
                  {{ selectedResource?.description }}
                </a-descriptions-item>
              </a-descriptions>
            </a-tab-pane>

            <a-tab-pane key="properties" tab="属性配置">
              <div v-if="selectedResource?.attributes">
                <pre>{{ formatJson(selectedResource.attributes) }}</pre>
              </div>
              <a-empty v-else description="暂无属性配置" />
            </a-tab-pane>

            <a-tab-pane key="pricing" tab="计价策略">
              <div v-if="selectedResource?.pricing">
                <pre>{{ formatJson(selectedResource.pricing) }}</pre>
              </div>
              <a-empty v-else description="暂无计价策略" />
            </a-tab-pane>

            <a-tab-pane key="logs" tab="日志记录">
              <a-timeline>
                <a-timeline-item
                  v-for="log in getResourceLogs(selectedResource?.id)"
                  :key="log.id"
                >
                  <p>{{ log.action }} - {{ log.create_time }}</p>
                  <p>{{ log.description }}</p>
                </a-timeline-item>
              </a-timeline>
            </a-tab-pane>
          </a-tabs>
        </div>
      </div>

      <!-- 右侧详情抽屉 -->
      <ResourceDetail
        :visible="detailDrawerVisible"
        :resource="selectedResource"
        class="resource-detail-drawer"
        @close="handleDetailDrawerClose"
        @edit-properties="handleEditProperties"
        @edit-pricing="handleEditPricing"
      />
    </div>

    <!-- 右键菜单 -->
    <a-dropdown
      :open="contextMenuVisible"
      :trigger="['contextmenu']"
      placement="bottomLeft"
    >
      <div class="context-menu-trigger"></div>
      <template #overlay>
        <a-menu @click="handleContextMenuClick">
          <a-menu-item key="add-child">
            <IconifyIcon icon="ant-design:plus-outlined" />
            新增子资源
          </a-menu-item>
          <a-menu-item key="copy">
            <IconifyIcon icon="ant-design:copy-outlined" />
            复制
          </a-menu-item>
          <a-menu-item key="delete" danger>
            <IconifyIcon icon="ant-design:delete-outlined" />
            删除
          </a-menu-item>
        </a-menu>
      </template>
    </a-dropdown>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue';
import { IconifyIcon } from '@vben/icons';
import { message, Modal } from 'ant-design-vue';
import { getResources } from '#/api/resource-center';
import { ResourceSidebar, ResourceList, ResourceDetail } from './components';

// 响应式数据
const treeLoading = ref(false);
const childrenLoading = ref(false);
const resourceList = ref<any[]>([]);
const resourceTree = ref<any[]>([]);
const childrenResources = ref<any[]>([]);
const selectedResourceId = ref<null | string>(null);
const selectedResource = ref<any>(null);
const expandedKeys = ref<string[]>([]);
const selectedKeys = ref<string[]>([]);
// const treeSearchKeyword = ref(''); // 暂时不需要

// 布局相关数据
const sidebarCollapsed = ref(false);
const detailDrawerVisible = ref(false);
const contextMenuVisible = ref(false);

// 业务类型相关
const currentBusinessType = ref<string | null>(null);
const currentBusinessTypeName = ref<string>('');

// 面包屑导航
const breadcrumbItems = ref<any[]>([]);

// 分类相关数据
const activeCategory = ref('all');
const selectedCustomTag = ref<string | null>(null);

// 自定义标签配置
const customTags = ref([
  { key: 'hot', name: '热门资源', color: '#f5222d', count: 0 },
  { key: 'new', name: '新增资源', color: '#52c41a', count: 0 },
  { key: 'maintenance', name: '维护中', color: '#fa8c16', count: 0 },
  { key: 'offline', name: '已下线', color: '#666666', count: 0 },
]);

// 列表视图数据
// const viewMode = ref('table'); // 'table' or 'card' - 暂时不需要
const listSearchKeyword = ref('');
const resourceTypeFilter = ref<string | null>(null);
const statusFilter = ref<string | null>(null);
const listLoading = ref(false);
const listPagination = ref({
  pageSize: 10,
  current: 1,
  total: 0,
});

// 新增：当前视图模式状态
const currentViewMode = ref<'list' | 'detail'>('list'); // list: 子资源列表,list detail: 资源详情
const isLeafNode = ref(false); // 是否为叶子节点
const activeTab = ref('basic'); // 详情面板的当前标签页
const treeSearchKeyword = ref(''); // 树搜索关键词

// 列表列配置
const listColumns = [
  {
    title: '资源名称',
    key: 'name',
    width: 250,
  },
  {
    title: '资源类型',
    key: 'resource_type',
    width: 120,
  },
  {
    title: '业务类型',
    key: 'business_type',
    width: 120,
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

// 子资源表格列配置
const childrenColumns = [
  {
    title: '资源名称',
    key: 'name',
    width: 200,
  },
  {
    title: '资源类型',
    key: 'resource_type',
    width: 120,
  },
  {
    title: '描述',
    key: 'description',
    width: 200,
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
  },
];

// 资源类型配置
const resourceTypeConfig = {
  PHYSICAL: {
    label: '物理资源',
    color: '#52c41a',
    icon: 'ant-design:database-outlined',
  },
  HUMAN: {
    label: '人力资源',
    color: '#1890ff',
    icon: 'ant-design:team-outlined',
  },
  DIGITAL: {
    label: '数字资源',
    color: '#722ed1',
    icon: 'ant-design:cloud-outlined',
  },
  SERVICE: {
    label: '服务资源',
    color: '#fa8c16',
    icon: 'ant-design:api-outlined',
  },
};

// 业务类型配置
const businessTypeConfig = {
  HOTEL: { color: '#1890ff', icon: 'ant-design:bank-outlined' },
  APARTMENT: { color: '#52c41a', icon: 'ant-design:home-outlined' },
  SPA: { color: '#eb2f96', icon: 'ant-design:heart-outlined' },
  SCENIC: { color: '#13c2c2', icon: 'ant-design:environment-outlined' },
  RESTAURANT: { color: '#fa8c16', icon: 'ant-design:coffee-outlined' },
  MEDICAL_BEAUTY: {
    color: '#722ed1',
    icon: 'ant-design:medicine-box-outlined',
  },
  BEAUTY_SALON: { color: '#eb2f96', icon: 'ant-design:scissor-outlined' },
};

// 工具函数
const getResourceTypeLabel = (type: string) => {
  return (
    resourceTypeConfig[type as keyof typeof resourceTypeConfig]?.label || type
  );
};

const getResourceTypeColor = (type: string) => {
  return (
    resourceTypeConfig[type as keyof typeof resourceTypeConfig]?.color || '#666'
  );
};

const getBusinessTypeColor = (type: string) => {
  return (
    businessTypeConfig[type as keyof typeof businessTypeConfig]?.color || '#666'
  );
};

const getResourceTypeIcon = (type: string) => {
  return (
    resourceTypeConfig[type as keyof typeof resourceTypeConfig]?.icon ||
    'ant-design:file-outlined'
  );
};

const getBusinessTypeIcon = (type: string) => {
  return (
    businessTypeConfig[type as keyof typeof businessTypeConfig]?.icon ||
    'ant-design:file-outlined'
  );
};

const formatJson = (jsonString: string) => {
  try {
    return JSON.stringify(JSON.parse(jsonString), null, 2);
  } catch {
    return jsonString;
  }
};

// 获取资源日志记录
const getResourceLogs = (resourceId: string | number) => {
  // 模拟日志数据
  return [
    {
      id: 1,
      action: '创建资源',
      description: '资源创建成功',
      create_time: '2024-01-15 10:30:00',
    },
    {
      id: 2,
      action: '更新属性',
      description: '更新了资源属性配置',
      create_time: '2024-01-16 14:20:00',
    },
    {
      id: 3,
      action: '状态变更',
      description: '资源状态从禁用改为启用',
      create_time: '2024-01-17 09:15:00',
    },
  ];
};

const getCapabilities = (capabilitiesString: string) => {
  try {
    const capabilities = JSON.parse(capabilitiesString);
    if (Array.isArray(capabilities)) {
      return capabilities;
    } else if (typeof capabilities === 'object') {
      // 如果是对象格式，转换为数组
      return Object.entries(capabilities).map(
        ([key, value]: [string, any]) => ({
          id: key,
          name: value.name || key,
          description: value.description || '',
          enabled: value.enabled || false,
          icon: value.icon || 'ant-design:setting-outlined',
          color: value.color || '#666',
        }),
      );
    }
    return [];
  } catch {
    return [];
  }
};

// 计算属性
const currentResources = computed(() => {
  // 如果有选中的资源，显示其子资源
  if (selectedResource.value) {
    return childrenResources.value;
  }

  // 根据当前分类标签过滤资源
  let filtered = resourceList.value;

  // 根据活动分类过滤
  if (activeCategory.value === 'type' && resourceTypeFilter.value) {
    filtered = filtered.filter(
      (r) => r.resource_type === resourceTypeFilter.value,
    );
  } else if (activeCategory.value === 'business' && statusFilter.value) {
    // 这里可以根据业务需求添加业务类型过滤
  } else if (activeCategory.value === 'custom' && selectedCustomTag.value) {
    // 根据自定义标签过滤
    switch (selectedCustomTag.value) {
      case 'hot':
        filtered = filtered.filter(
          (r) => r.metadata && JSON.parse(r.metadata).is_hot,
        );
        break;
      case 'new':
        filtered = filtered.filter(
          (r) =>
            r.create_time &&
            new Date(r.create_time) >
              new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
        );
        break;
      case 'maintenance':
        filtered = filtered.filter((r) => r.status === 0);
        break;
      case 'offline':
        filtered = filtered.filter((r) => r.status === 0);
        break;
    }
  }

  // 应用搜索关键词过滤
  if (listSearchKeyword.value) {
    const keyword = listSearchKeyword.value.toLowerCase();
    filtered = filtered.filter(
      (r) =>
        r.name.toLowerCase().includes(keyword) ||
        r.code.toLowerCase().includes(keyword) ||
        r.description.toLowerCase().includes(keyword),
    );
  }

  // 应用资源类型过滤
  if (resourceTypeFilter.value) {
    filtered = filtered.filter(
      (r) => r.resource_type === resourceTypeFilter.value,
    );
  }

  // 应用状态过滤
  if (statusFilter.value !== null) {
    const status = parseInt(statusFilter.value);
    filtered = filtered.filter((r) => r.status === status);
  }

  return filtered;
});

const typeTree = computed(() => {
  const typeMap = new Map();

  resourceList.value.forEach((resource) => {
    const type = resource.resource_type;
    if (!typeMap.has(type)) {
      typeMap.set(type, {
        key: `type-${type}`,
        title: getResourceTypeLabel(type),
        type,
        count: 0,
        children: [],
      });
    }
    typeMap.get(type).count++;
    typeMap.get(type).children.push({
      key: resource.id.toString(),
      title: resource.name,
      resource,
    });
  });

  return Array.from(typeMap.values());
});

const businessTree = computed(() => {
  const businessMap = new Map();

  resourceList.value.forEach((resource) => {
    const business = resource.business_type;
    if (!businessMap.has(business)) {
      businessMap.set(business, {
        key: `business-${business}`,
        title: resource.business_type_name,
        business,
        count: 0,
        children: [],
      });
    }
    businessMap.get(business).count++;
    businessMap.get(business).children.push({
      key: resource.id.toString(),
      title: resource.name,
      resource,
    });
  });

  return Array.from(businessMap.values());
});

const customTagTree = computed(() => {
  if (!selectedCustomTag.value) return [];

  // 根据选中的自定义标签过滤资源
  const filteredResources = resourceList.value.filter((resource) => {
    // 这里可以根据实际业务逻辑实现标签过滤
    switch (selectedCustomTag.value) {
      case 'hot':
        return resource.metadata && JSON.parse(resource.metadata).is_hot;
      case 'new':
        return (
          resource.create_time &&
          new Date(resource.create_time) >
            new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)
        );
      case 'maintenance':
        return resource.status === 0;
      case 'offline':
        return resource.status === 0;
      default:
        return false;
    }
  });

  return buildResourceTree(filteredResources);
});

// 构建资源树
const buildResourceTree = (resources: any[]) => {
  const resourceMap = new Map();
  const tree: any[] = [];
  treetree;

  // 创建资源映射
  resources.forEach((resource) => {
    resourceMap.set(resource.id, {
      key: resource.id.toString(),
      title: resource.name,
      children: [],
      resource,
    });
  });

  // 构建树形结构
  resources.forEach((resource) => {
    const node = resourceMap.get(resource.id);
    if (resource.parent_id) {
      const parent = resourceMap.get(resource.parent_id);
      if (parent) {
        parent.children.push(node);
      }
    } else {
      tree.push(node);
    }
  });

  return tree;
};

// 更新自定义标签计数
const updateCustomTagCounts = () => {
  customTags.value.forEach((tag) => {
    switch (tag.key) {
      case 'hot':
        tag.count = resourceList.value.filter(
          (r) => r.metadata && JSON.parse(r.metadata).is_hot,
        ).length;
        break;
      case 'new':
        tag.count = resourceList.value.filter(
          (r) =>
            r.create_time &&
            new Date(r.create_time) >
              new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
        ).length;
        break;
      case 'maintenance':
        tag.count = resourceList.value.filter((r) => r.status === 0).length;
        break;
      case 'offline':
        tag.count = resourceList.value.filter((r) => r.status === 0).length;
        break;
    }
  });
};

// 加载资源树
const loadResourceTree = async () => {
  treeLoading.value = true;
  try {
    const result = await getResources({ pageSize: 1000 });
    const resources = result.items;
    resourceList.value = resources;
    resourceTree.value = buildResourceTree(resources);
    expandedKeys.value = resourceTree.value.map((node) => node.key);

    // 更新自定义标签计数
    updateCustomTagCounts();
  } catch (error) {
    console.error('Failed to load resource tree:', error);
    message.error('加载资源树失败');
  } finally {
    treeLoading.value = false;
  }
};

// 加载子资源
const loadChildrenResources = async (parentId: string) => {
  childrenLoading.value = true;
  try {
    const result = await getResources({ parent_id: parentId, pageSize: 1000 });
    childrenResources.value = result.items;
    // 更新分页信息
    listPagination.value.total = result.items.length;
    listPagination.value.current = 1;
    return Promise.resolve(); // 返回Promise以便链式调用
  } catch (error) {
    console.error('Failed to load children resources:', error);
    message.error('加载子资源失败');
    return Promise.reject(error);
  } finally {
    childrenLoading.value = false;
  }
};

// 树节点选择
const handleTreeSelect = (keys: string[]) => {
  selectedKeys.value = keys;
  selectedResourceId.value = keys[0] || null;

  // 重置分页信息
  listPagination.value.current = 1;
  listPagination.value.total = 0;

  if (selectedResourceId.value) {
    const resource = resourceList.value.find(
      (r) => r.id.toString() === selectedResourceId.value,
    );
    if (resource) {
      selectedResource.value = resource;

      // 检查是否为叶子节点（通过检查是否有子资源）
      loadChildrenResources(selectedResourceId.value).then(() => {
        if (childrenResources.value.length > 0) {
          // 有子节点，显示子资源列表
          currentViewMode.value = 'list';
          isLeafNode.value = false;
          // 更新分页信息
          listPagination.value.total = childrenResources.value.length;
        } else {
          // 无子节点，显示资源详情
          currentViewMode.value = 'detail';
          isLeafNode.value = true;
          // 不自动打开详情抽屉，直接在中间区域显示详情
          detailDrawerVisible.value = false;
        }
      });
    }
  } else {
    selectedResource.value = null;
    childrenResources.value = [];
    currentViewMode.value = 'list';
    isLeafNode.value = false;
    // 重置为根级资源列表的分页
    loadResourceList();
  }
};

// 类型树选择
const handleTypeTreeSelect = (keys: string[]) => {
  const key = keys[0];
  if (key && key.startsWith('type-')) {
    // 选择的是类型节点，不处理
    return;
  }
  handleTreeSelect(keys);
};

// 业务树选择
const handleBusinessTreeSelect = (keys: string[]) => {
  const key = keys[0];
  if (key && key.startsWith('business-')) {
    // 选择的是业务节点，不处理
    return;
  }
  handleTreeSelect(keys);
};

// 分类切换
const handleCategoryChange = (category: string) => {
  activeCategory.value = category;
  selectedCustomTag.value = null;
  selectedKeys.value = [];
  selectedResourceId.value = null;
  selectedResource.value = null;
  childrenResources.value = [];
  // 重置视图模式为列表模式
  currentViewMode.value = 'list';
  isLeafNode.value = false;
  // 重置分页信息
  listPagination.value.current = 1;
  listPagination.value.total = 0;
  // 重新加载资源列表
  loadResourceList();
};

// 自定义标签点击
const handleCustomTagClick = (tag: any) => {
  selectedCustomTag.value =
    selectedCustomTag.value === tag.key ? null : tag.key;
  selectedCustomTag.valuetag.keynullselectedCustomTag.valuetag.keynull;
  selectedKeys.value = [];
  selectedResourceId.value = null;
  selectedResource.value = null;
  childrenResources.value = [];
  // 重置视图模式为列表模式
  currentViewMode.value = 'list';
  isLeafNode.value = false;
  // 重置分页信息
  listPagination.value.current = 1;
  listPagination.value.total = 0;
  // 重新加载资源列表
  loadResourceList();
};

// 树节点展开
const handleTreeExpand = (keys: string[]) => {
  expandedKeys.value = keys;
};

// 树搜索
const handleTreeSearch = (keyword: string) => {
  treeSearchKeyword.value = keyword;

  if (!keyword.trim()) {
    // 如果搜索关键词为空，显示所有资源
    loadResourceTree();
    return;
  }

  // 根据关键词过滤资源树
  const filteredTree = filterResourceTree(
    resourceTree.value,
    keyword.toLowerCase(),
  );
  resourceTree.value = filteredTree;

  // 自动展开包含匹配项的节点
  const expandedNodes = getExpandedNodesForSearch(
    resourceTree.value,
    keyword.toLowerCase(),
  );
  expandedKeys.value = expandedNodes;
};

// 过滤资源树的辅助函数
const filterResourceTree = (tree: any[], keyword: string): any[] => {
  return tree.filter((node) => {
    // 检查当前节点是否匹配
    const nodeMatches =
      node.title.toLowerCase().includes(keyword) ||
      (node.resource &&
        node.resource.name &&
        node.resource.name.toLowerCase().includes(keyword)) ||
      (node.resource &&
        node.resource.code &&
        node.resource.code.toLowerCase().includes(keyword));

    // 递归检查子节点
    if (node.children && node.children.length > 0) {
      const filteredChildren = filterResourceTree(node.children, keyword);
      if (filteredChildren.length > 0) {
        node.children = filteredChildren;
        return true;
      }
    }

    return nodeMatches;
  });
};

// 获取需要展开的节点
const getExpandedNodesForSearch = (tree: any[], keyword: string): string[] => {
  const expandedNodes: string[] = [];
  expandedNodesexpandedNodes;

  const traverse = (nodes: any[]) => {
    nodes.forEach((node) => {
      const nodeMatches =
        node.title.toLowerCase().includes(keyword) ||
        (node.resource &&
          node.resource.name &&
          node.resource.name.toLowerCase().includes(keyword)) ||
        (node.resource &&
          node.resource.code &&
          node.resource.code.toLowerCase().includes(keyword));

      if (nodeMatches) {
        // 如果当前节点匹配，展开其所有父节点
        let parent = node.parent;
        while (parent) {
          if (!expandedNodes.includes(parent.key)) {
            expandedNodes.push(parent.key);
          }
          parent = parent.parent;
        }
      }

      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    });
  };

  traverse(tree);
  return expandedNodes;
};

// 列表搜索
const handleListSearch = () => {
  // 实现列表搜索逻辑
  // 列表搜索功能已实现
};

// 列表过滤
const handleFilterChange = () => {
  // 实现列表过滤逻辑
  // 列表过滤功能已实现
};

// 列表分页
const handleTableChange = (pagination: any) => {
  listPagination.value = pagination;
  // 根据当前视图和过滤条件重新加载列表数据
  loadResourceList();
};

// 列表数据加载
const loadResourceList = async () => {
  listLoading.value = true;
  try {
    const params: any = {
      page: listPagination.value.current,
      pageSize: listPagination.value.pageSize,
    };
    if (resourceTypeFilter.value) {
      params.resource_type = resourceTypeFilter.value;
    }
    if (statusFilter.value) {
      params.status = statusFilter.value;
    }
    if (listSearchKeyword.value) {
      params.keyword = listSearchKeyword.value;
    }

    const result = await getResources(params);
    resourceList.value = result.items;
    listPagination.value.total = result.total;
  } catch (error) {
    console.error('Failed to load resource list:', error);
    message.error('加载资源列表失败');
  } finally {
    listLoading.value = false;
  }
};

// 卡片点击
const handleCardClick = (resource: any) => {
  selectedResourceId.value = resource.id.toString();
  selectedResource.value = resource;
  loadChildrenResources(resource.id.toString());
};

// 方法
const handleCreateResource = () => {
  message.info('创建资源功能');
};

const handleView = (record: any) => {
  selectedResource.value = record;
  detailDrawerVisible.value = true;
  // 设置抽屉框宽度为90%
  document.documentElement.style.setProperty('--drawer-width', '90%');
};

const handleEdit = (record: any) => {
  message.info(`编辑资源: ${record.name}`);
};

const handleDelete = (record: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除资源"${record.name}"吗？`,
    onOk: () => {
      message.success('删除成功');
      loadResourceList(); // 刷新列表
    },
  });
};

const handleExport = () => {
  message.info('导出功能开发中');
};

// 新增的处理函数
const handleBatchImport = () => {
  message.info('批量导入功能开发中');
};

const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value;
};

const handleTreeRightClick = (event: any) => {
  contextMenuVisible.value = true;
  // TODO: 处理右键菜单逻辑TODOTODO
};

const handleResourceClick = (resource: any) => {
  selectedResourceId.value = resource.id.toString();
  selectedResource.value = resource;
  detailDrawerVisible.value = true;
  loadChildrenResources(resource.id.toString());
};

const handleDetailDrawerClose = () => {
  detailDrawerVisible.value = false;
};

const handleEditProperties = (resource: any) => {
  message.info(`编辑属性: ${resource.name}`);
  // TODO: 打开属性编辑弹窗TODOTODO
};

const handleEditPricing = (resource: any) => {
  message.info(`设置价格: ${resource.name}`);
  // TODO: 打开价格设置弹窗TODOTODO
};

const handleBreadcrumbClick = (item: any, index: number) => {
  // TODO: 处理面包屑导航点击
  console.log('Breadcrumb click:', item, index);
  TODOTODO;
};

const handleContextMenuClick = ({ key }: { key: string }) => {
  contextMenuVisible.value = false;
  switch (key) {
    case 'add-child':
      message.info('新增子资源');
      break;
    case 'copy':
      message.info('复制资源');
      break;
    case 'delete':
      message.info('删除资源');
      break;
  }
};

// 获取列表标题
const getListTitle = () => {
  // 根据当前视图模式返回不同标题
  if (currentViewMode.value === 'detail') {
    return `${selectedResource.value?.name || '资源'}详情`;
  }

  if (selectedResource.value) {
    return `${selectedResource.value.name}的子资源列表`;
  }

  if (resourceTypeFilter.value) {
    return `${getResourceTypeLabel(resourceTypeFilter.value)}资源列表`;
  }
  if (statusFilter.value) {
    return `${statusFilter.value === '1' ? '启用' : '禁用'}资源列表`;
  }
  if (listSearchKeyword.value) {
    return `搜索"${listSearchKeyword.value}"的资源列表`;
  }
  return '资源列表';
};

// 生命周期
onMounted(() => {
  loadResourceTree();
  loadResourceList(); // 初始加载列表
});
</script>

<style lang="less" scoped>
.resource-catalog {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background: #fff;
    border-bottom: 1px solid #f0f0f0;
    flex-shrink: 0;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      h2 {
        margin: 0;
        font-size: 20px;
      }
    }

    .header-actions {
      display: flex;
      align-items: center;
    }
  }

  .catalog-layout {
    display: flex;
    gap: 16px;
    min-height: calc(100vh - 200px);

    .catalog-sidebar {
      width: 320px;
      flex-shrink: 0;

      .tree-search {
        margin-bottom: 16px;
      }

      .quick-categories {
        .category-content {
          .custom-tags {
            margin-bottom: 16px;

            .ant-tag {
              cursor: pointer;
              margin-bottom: 8px;

              &.active {
                border-color: #1890ff;
                color: #1890ff;
              }
            }
          }
        }
      }

      .tree-node {
        display: flex;
        align-items: center;
        gap: 8px;
        width: 100%;

        .node-title {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }

    .catalog-main {
      flex: 1;
      display: flex;
      flex-direction: column;
      gap: 16px;

      .list-header {
        .list-controls {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;

          .list-title {
            display: flex;
            align-items: center;
            gap: 10px;

            h3 {
              margin: 0;
              font-size: 18px;
            }

            .resource-count {
              font-size: 14px;
              color: #888;
            }
          }

          .list-actions {
            display: flex;
            align-items: center;
            gap: 10px;

            .ant-radio-group {
              .ant-radio-button {
                display: flex;
                align-items: center;
                gap: 4px;
              }
            }
          }
        }
      }

      .list-content {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 16px;

        .table-view,
        .card-view {
          background: #fff;
          border-radius: 4px;
          padding: 12px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

          .resource-name {
            display: flex;
            align-items: center;
            gap: 8px;

            .name-info {
              display: flex;
              flex-direction: column;
            }
          }

          .resource-card {
            &.selected {
              border: 1px solid #1890ff;
              box-shadow: 0 0 10px rgba(24, 144, 255, 0.3);
            }

            .card-cover {
              display: flex;
              justify-content: center;
              align-items: center;
              height: 100px;
              background: #f0f2f5;
              border-radius: 4px 4px 0 0;
            }

            .card-title {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;

              .name {
                font-size: 16px;
                font-weight: bold;
                color: #333;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }
            }

            .card-content {
              .description {
                font-size: 14px;
                color: #666;
                margin-bottom: 8px;
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
              }

              .tags {
                display: flex;
                flex-wrap: wrap;
                gap: 4px;
              }
            }
          }
        }

        .detail-card {
          .properties-section,
          .constraints-section,
          .metadata-section {
            background: #f5f5f5;
            padding: 12px;
            border-radius: 4px;

            pre {
              margin: 0;
              font-size: 12px;
              line-height: 1.4;
            }
          }

          .capabilities-section {
            .capability-card {
              margin-bottom: 8px;

              .capability-title {
                display: flex;
                align-items: center;
                gap: 8px;
              }
            }
          }
        }

        .children-card {
          .resource-name {
            display: flex;
            align-items: center;
            gap: 8px;
          }
        }

        .empty-card {
          display: flex;
          align-items: center;
          justify-content: center;
          min-height: 400px;
        }
      }
    }

    // 列表面板样式
    .list-panel {
      flex: 1;
      width: 100%;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      overflow: hidden;
    }

    // 详情面板样式
    .detail-panel {
      flex: 1;
      width: 100%;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      overflow: hidden;

      .detail-header {
        padding: 20px 24px;
        border-bottom: 1px solid #f0f0f0;
        background: #fafafa;

        .detail-title {
          display: flex;
          align-items: center;
          gap: 12px;
          margin-top: 12px;

          h3 {
            margin: 0;
            font-size: 18px;
            font-weight: 600;
            color: #333;
          }
        }
      }

      .detail-content {
        padding: 24px;

        .ant-tabs {
          .ant-tabs-content {
            .ant-descriptions {
              margin-top: 16px;
            }

            pre {
              background: #f5f5f5;
              padding: 12px;
              border-radius: 4px;
              font-size: 12px;
              line-height: 1.5;
              overflow-x: auto;
            }

            .ant-timeline {
              margin-top: 16px;

              .ant-timeline-item {
                .ant-timeline-item-content {
                  p {
                    margin: 0;
                    line-height: 1.5;

                    &:first-child {
                      font-weight: 500;
                      color: #333;
                    }

                    &:last-child {
                      color: #666;
                      font-size: 13px;
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
// 抽屉框样式
.resource-detail-drawer {
  width: 70% !important;
}
</style>
